﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Security;

namespace WsdShop.Common
{
    public class SecurityHelper
    {
        //MD5
        public static string MD5(string str, bool IsLower = true)
        {
            string s = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            if (IsLower)
                s = s.ToLower();
            else
                s = s.ToUpper();
            return s;
        }


        public static string CreateMD5(string str)
        {
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] encryptedBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < encryptedBytes.Length; i++)
                {
                    sb.AppendFormat("{0:X2}", encryptedBytes[i]);
                    //16进制保留两位有效数字
                }
                //return sb.ToString();
                //16位带26-C9-DA-4B-CF-FC-0F-F9
                string value = BitConverter.ToString(encryptedBytes, 4, 8);
                value = value.Replace("-", "").ToLower();
                return value;
            }
            catch (Exception err)
            {
                return "error";
            }
        }


        public static string SHA1(string orgStr)
        {
            string strResult = "";
            System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
            byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(orgStr));
            for (int i = 0; i < bytResult.Length; i++)
            {
                strResult = strResult + bytResult[i].ToString("x2");
            }
            return strResult;
        }

        #region DES

        //DES加密
        public static string DESEncrypt(string str, string des_key, string des_offset)
        {
            try
            {
                //string des_key = ConfigurationManager.AppSettings["DES_Key"];
                //string des_offset = ConfigurationManager.AppSettings["DES_Offset"];
                //string des_key = "!@#$5rfvbhu876+_";
                //string des_offset = "";
                byte[] bytIn = System.Text.Encoding.UTF8.GetBytes(str);
                string ky = des_key;
                string i_v = des_offset;
                byte[] buffer_key = Convert.FromBase64String(ky);
                byte[] buffer_iv = Convert.FromBase64String(i_v);
                DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();
                ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(buffer_key, buffer_iv);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
                cs.Write(bytIn, 0, bytIn.Length);
                cs.FlushFinalBlock();
                return System.Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception error)
            {
                return "error";
            }

        }




        //DES加密
        public static string DESEncrypt(string str)
        {
            try
            {
                //string des_key = ConfigurationManager.AppSettings["DES_Key"];
                //string des_offset = ConfigurationManager.AppSettings["DES_Offset"];
                string des_key = "!@#$5rfvbhu876+_";
                string des_offset = "";
                byte[] bytIn = System.Text.Encoding.UTF8.GetBytes(str);
                string ky = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(des_key));
                string i_v = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(des_offset));
                byte[] buffer_key = Convert.FromBase64String(ky);
                byte[] buffer_iv = Convert.FromBase64String(i_v);
                DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();
                ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(buffer_key, buffer_iv);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
                cs.Write(bytIn, 0, bytIn.Length);
                cs.FlushFinalBlock();
                return System.Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception error)
            {
                return "error";
            }

        }
        //DES解密
        public static string DESDecrypt(string str)
        {
            try
            {
                string des_key = "";
                string des_offset = "";

                byte[] bytIn = System.Convert.FromBase64String(str);
                string ky = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(des_key));
                string i_v = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(des_offset));
                byte[] buffer_key = Convert.FromBase64String(ky);
                byte[] buffer_iv = Convert.FromBase64String(i_v);

                DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();
                ICryptoTransform decrypto = mobjCryptoService.CreateDecryptor(buffer_key, buffer_iv);

                MemoryStream straem = new MemoryStream();
                CryptoStream cs = new CryptoStream(straem, decrypto, CryptoStreamMode.Write);
                cs.Write(bytIn, 0, bytIn.Length);
                cs.FlushFinalBlock();
                cs.Close();
                return Encoding.UTF8.GetString(straem.ToArray());
            }
            catch (Exception err)
            {
                return "error";
            }
        }
        #endregion

        #region AES

        //AES加密
        public static string AESEncrypt(string str)
        {
            try
            {
                string aes_key = "";
                string aes_offset = "";
                SymmetricAlgorithm des = Rijndael.Create();
                byte[] strarray = Encoding.UTF8.GetBytes(str);
                byte[] buffer_key = Base64_FromBase64(aes_key);
                byte[] buffer_iv = Base64_FromBase64(aes_offset);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(buffer_key, buffer_iv), CryptoStreamMode.Write);
                cs.Write(strarray, 0, strarray.Length);
                cs.FlushFinalBlock();
                cs.Close();
                byte[] ms_array = ms.ToArray();
                ms.Close();
                return System.Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception err)
            {
                return "error";
            }
        }
        //AES解密
        public static string AESDecrypt(string str)
        {
            try
            {
                string aes_key = "";
                string aes_offset = "";
                SymmetricAlgorithm des = Rijndael.Create();
                byte[] strarray = System.Convert.FromBase64String(str);
                byte[] buffer_key = Base64_FromBase64(aes_key);
                byte[] buffer_iv = Base64_FromBase64(aes_offset);
                byte[] decryptBytes = new byte[strarray.Length];
                MemoryStream ms = new MemoryStream(strarray);
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(buffer_key, buffer_iv), CryptoStreamMode.Read);
                cs.Read(decryptBytes, 0, decryptBytes.Length);
                cs.Close();
                ms.Close();
                string s = Encoding.UTF8.GetString(decryptBytes);
                s = Regex.Replace(s, @"\0", "");
                return s;
            }
            catch (Exception err)
            {
                return "error";
            }

        }
        //Base转换
        public static byte[] Base64_FromBase64(string str)
        {
            string b64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str));
            byte[] from_b64 = Convert.FromBase64String(b64);
            return from_b64;
        }
        #endregion



        /// <summary>
        /// Des加密
        /// </summary>
        /// <param name="original"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] DESEncrypt(byte[] original, byte[] key)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                var des = new DESCryptoServiceProvider();
                des.Key = key;
                des.IV = key;
                var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(original, 0, original.Length);
                cs.FlushFinalBlock();
                cs.Close();
                cs.Dispose();

                return ms.ToArray();
            }
        }

        /// <summary>
        /// md5加密，32位
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Md5Encrypt(string text)
        {
            var originalBytes = Encoding.Default.GetBytes(text);
            byte[] encodedBytes;
            using (var md5 = new MD5CryptoServiceProvider())
            {
                encodedBytes = md5.ComputeHash(originalBytes);
            }
            return ToHexString(encodedBytes);
        }
        /// <summary>
        /// 转换成16进制的字符串形式。
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes)
        {
            int chArrayLength = bytes.Length * 2;
            var chArray = new char[chArrayLength];
            int index = 0;
            for (var i = 0; i < chArrayLength; i += 2)
            {
                byte b = bytes[index++];
                chArray[i] = GetHexValue(b / 16);
                chArray[i + 1] = GetHexValue(b % 16);
            }
            return new String(chArray);
        }

        private static char GetHexValue(int i)
        {
            if (i < 10)
            {
                return (char)(i + '0');
            }
            return (char)(i - 10 + 'A');
        }
    }
}
